package com.storage.system.utils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.storage.common.core.domain.ServiceResponse;
import com.storage.common.enums.OwnerType;
import com.storage.common.jpush.JiGuangPushUtil;
import com.storage.common.utils.GsonUtil;
import com.storage.system.domain.*;
import com.storage.system.mapper.StorageGoodsMapper;
import com.storage.system.mapper.StorageNoticeMessageMapper;
import com.storage.system.mapper.StorageShopMapper;
import com.storage.system.mapper.StorageUserMapper;
import com.storage.system.service.impl.StorageProcurementOrderServiceImpl;
import com.storage.system.vo.GoodsDetailInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 业务转换工具类
 *
 * @author wb-zh270168
 */
@Component
public class GoodsConvertUtils {

    private static final Logger logger = LoggerFactory.getLogger(StorageProcurementOrderServiceImpl.class);

    public static Gson gson = GsonUtil.getGson();

    @Autowired
    private StorageGoodsMapper storageGoodsMapper;

    @Autowired
    private StorageUserMapper storageUserMapper;

    @Autowired
    private StorageShopMapper storageShopMapper;

    @Autowired
    private StorageNoticeMessageMapper storageNoticeMessageMapper;

    private static GoodsConvertUtils goodsConvertUtils;

    @PostConstruct
    public void init() {
        goodsConvertUtils = this;
        goodsConvertUtils.storageGoodsMapper = this.storageGoodsMapper;
        goodsConvertUtils.storageUserMapper = this.storageUserMapper;
        goodsConvertUtils.storageShopMapper = this.storageShopMapper;
        goodsConvertUtils.storageNoticeMessageMapper = this.storageNoticeMessageMapper;
    }

    /**
     * 重新处理详情逻辑 - 处理为如下的样子
     * [
     *     {
     *         "颜色": "红",
     *         "尺码": [
     *             {"值": "s", "数量": 100},
     *             {"值": "m", "数量": 100},
     *             {"值": "l", "数量": 100},
     *         ],
     *         "进货价"：100,
     *         "批发价"：100,
     *         "零售价"：100,
     *         "总库存"：100,
     *     }
     * ]
     */
    public static void convert(StorageProduct product) {
        List<GoodsDetailInfo> goodsDetailInfos = new ArrayList<>();
        // 按照进 颜色、货价、批发价、零售价分组goods
        Map<String, List<StorageGoods>> collect = product.getGoods().stream().collect(Collectors.groupingBy(e -> e.getColor() + "#" + e.getPurchasePrice() + "#" + e.getTradePrice() + "#" + e.getRetailPrice()));
        for (String key : collect.keySet()) {
            // 单个item
            GoodsDetailInfo goodsDetailInfo = new GoodsDetailInfo();
            List<GoodsDetailInfo.PropertiesValue> propertiesValues = new ArrayList<>();

            for (StorageGoods good : collect.get(key)) {
                // 赋值
                goodsDetailInfo.setPurchasePrice(good.getPurchasePrice());
                goodsDetailInfo.setWarning(good.getWarning());
                goodsDetailInfo.setRetailPrice(good.getRetailPrice());
                goodsDetailInfo.setTradePrice(good.getTradePrice());
                if (goodsDetailInfo.getTotalStock() == null) {
                    goodsDetailInfo.setTotalStock(good.getStockNum());
                } else {
                    goodsDetailInfo.setTotalStock(goodsDetailInfo.getTotalStock() + good.getStockNum());
                }

                // 解析详情
                String propertiesDetail = good.getPropertiesDetail();

                List<Map<String, String>> list = gson.fromJson(propertiesDetail, new TypeToken<List<Map<String, String>>>() {
                }.getType());
                list.stream().forEach(tempItem -> {
                    String k = tempItem.keySet().stream().findFirst().orElse(null);
                    String value = tempItem.get(k);
                    if (Objects.equals("颜色", k)) {
                        goodsDetailInfo.setPropertieName(value);
                    }
                    if (Objects.equals("尺码", k)) {
                        GoodsDetailInfo.PropertiesValue propertiesValue = goodsDetailInfo.new PropertiesValue();
                        propertiesValue.setPropertiesValue(value);
                        propertiesValue.setId(good.getId());
                        propertiesValue.setStock(good.getStockNum());
                        propertiesValues.add(propertiesValue);
                    }

                });
            }
            goodsDetailInfo.setPropertiesValues(propertiesValues);
            // 添加单个item
            goodsDetailInfos.add(goodsDetailInfo);
        }
        // 放入product中
        product.setGoodsDetailInfos(goodsDetailInfos);

        changeForAndriod(product);
    }

    /**
     * 转换给安卓
     *
     * @param product
     */
    public static void changeForAndriod(StorageProduct product) {
        for (StorageGoods good : product.getGoods()) {
            // 将单品的属性集合解析成候鸣需要的样子for andriod
            String propertiesDetail = good.getPropertiesDetail();
            List<Map<String, String>> list = gson.fromJson(propertiesDetail, new TypeToken<List<Map<String, String>>>() {
            }.getType());
            List<Map<String, String>> map = list.stream().map(item -> {
                String key = item.keySet().stream().findFirst().orElse(null);
                String value = item.get(key);
                Map<String, String> temp = new HashMap<>();
                temp.put("name", key);
                temp.put("value", value);
                if (Objects.equals("颜色", key)) {
                    good.setColor(value);
                }
                return temp;
            }).collect(Collectors.toList());
            good.setPropertiesDetailArr(map);
        }
    }

    /**
     * 判断当前是否达到预警条件
     * 条件：货号 + 颜色
     *
     * @param sourceGoods
     * @param sourceProduct
     * @return
     */
    public static Boolean checkWarning(StorageGoods sourceGoods, StorageProduct sourceProduct) {
        // 当前颜色单品所属颜色种类的所有其他单品
        Gson gson = GsonUtil.getGson();
        // 查询单品列表
        StorageGoods goodsCondition = new StorageGoods();
        goodsCondition.setProductId(sourceProduct.getId());
        goodsCondition.setCreateUserId(sourceProduct.getCreateUserId());
        goodsCondition.setOwnerType(sourceProduct.getOwnerType());
        List<StorageGoods> goodsList = goodsConvertUtils.storageGoodsMapper.selectStorageGoodsList(goodsCondition);

        String sourcePropertiesDetail = sourceGoods.getPropertiesDetail();
        List<Map<String, String>> sourceGoodsDetails = gson.fromJson(sourcePropertiesDetail, new TypeToken<List<Map<String, String>>>() {}.getType());
        String targetColor = sourceGoodsDetails.get(0).get("颜色");

        // 同样颜色的单品集合
        List<StorageGoods> targetGoods = new ArrayList<>();
        for (StorageGoods good : goodsList) {
            // 将单品的属性集合解析成候鸣需要的样子for andriod
            String propertiesDetail = good.getPropertiesDetail();
            List<Map<String, String>> list = gson.fromJson(propertiesDetail, new TypeToken<List<Map<String, String>>>() {
            }.getType());
            if (list != null && Objects.equals(list.get(0).get("颜色"), targetColor)) {
                targetGoods.add(good);
            }
        }

        // 同样颜色的单品库存总数
        LongSummaryStatistics summaryStatistics = targetGoods.stream().collect(Collectors.summarizingLong(StorageGoods::getStockNum));
        Long total = summaryStatistics.getSum();

        float percent = ((float)total / (float)sourceProduct.getTotalGoodsNum()) * 100;
        // 发送预警
        if (percent <= sourceGoods.getWarning()) {
            sendNotice(sourceGoods, sourceProduct);
        }
        return false;
    }

    /**
     * 达到预警推送库存告急通知
     *
     * @param sourceGoods
     * @param sourceProduct
     * @return
     */
    public static ServiceResponse<Boolean> sendNotice(StorageGoods sourceGoods, StorageProduct sourceProduct) {
        String phone = null;
        String title;
        sourceProduct.setGoods(new ArrayList<>());
        sourceProduct.getGoods().add(sourceGoods);
        GoodsConvertUtils.changeForAndriod(sourceProduct);

        List<Map<String, String>> propertiesValues = sourceProduct.getGoods().get(0).getPropertiesDetailArr();
        String standard = propertiesValues.stream().map(item -> String.format("%s：[%s]", item.get("name"), item.get("value")))
                .collect(Collectors.joining("; ")).concat(" 达到预警值，请及时补货！");
        title = String.format("货号：%s  规格：%s", sourceProduct.getProductSpuCode(), standard);


        String detailJson = gson.toJson(Arrays.asList(sourceProduct));
        // 实例：你当前
        if (sourceGoods.getOwnerType() == OwnerType.AGENT.getValue()) {
            StorageUser user = goodsConvertUtils.storageUserMapper.selectStorageUserById(sourceGoods.getCreateUserId());
            phone = user != null ? user.getPhone() : null;

        } else if (sourceGoods.getOwnerType() == OwnerType.SHOP.getValue()) {
            StorageShop shop = goodsConvertUtils.storageShopMapper.selectStorageShopById(sourceGoods.getCreateUserId());
            if (shop == null) {
                return new ServiceResponse<>(false, null, "当前单品所属店铺不存在无法进行预警推送");
            }
            // 查询当前店铺所属代理商将对应的单品预警推送给代理商
            StorageUser user = goodsConvertUtils.storageUserMapper.selectStorageUserById(shop.getCreateUserId());
            phone = user != null ? user.getPhone() : null;

            // 龙泉驿店 货品：0001 颜色：[红]; 尺码：[s] 达到预警值，请及时补货！
            title = String.format("店铺：%s %", shop.getShopName(), title);
        }

        if (phone == null) {
            logger.error("单品预警失败,未获取到电话");
            return new ServiceResponse<>(false, null, "单品预警失败,未获取到电话");
        }

        // 持久化消息记录
        StorageNoticeMessage noticeMessage = new StorageNoticeMessage(sourceProduct.getCreateUserId(), phone, detailJson, title);
        goodsConvertUtils.storageNoticeMessageMapper.insertStorageNoticeMessage(noticeMessage);

        JiGuangPushUtil.pushNotice(phone, title, detailJson, noticeMessage.getId());
        return new ServiceResponse<>(true, null, null);
    }
}
